<template>
  <div class="main">
    <div class="login_box">
      <div class="title">
        欢迎访问DevOps运维平台
      </div>
      <div class="login_form">
        <el-form :model="form" ref="form" :rules="rules" label-width="30px">
          <el-form-item prop="username">
            <el-input
                :prefix-icon="User"
                placeholder="用户名"
                v-model="form.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
                :prefix-icon="Lock"
                placeholder="密码"
                type="password"
                v-model="form.password"
                show-password
            ></el-input>
          </el-form-item>
          <el-form-item class="btn">
            <el-button type="primary" @click="onSubmit">登录</el-button>
          </el-form-item>
        </el-form>

      </div>
    </div>
  </div>
</template>
<script>
// input里加图标必须单独按需导入
import {User, Lock} from "@element-plus/icons-vue";

export default {
  name: 'Login',
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, message: '用户名长度应不小于3个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, message: '用户名长度应不小于6个字符', trigger: 'blur'}
        ]
      },
    }
  },
  methods: {
    onSubmit() {
      // 提交前预验证
      this.$refs.form.validate((valid) => {
        // 回调函数中valid布尔值
        if (valid) {
          // 登陆成功并给消息提示
          this.$http.post('/login/', this.form)
              .then(res => {
                if (res.data.code == 200) {
                  this.$message.success('登录成功');
                  // 保存token和用户到会话存储
                  window.sessionStorage.setItem('token', res.data.token)
                  window.sessionStorage.setItem('username', res.data.username)
                  this.$router.push('/dashboard/')
                }
              })
        } else {
          this.$message.warning('用户名或密码格式错误！')
        }
      })
    }
  },
  // 需要用setup导入
  setup() {
    return {
      User, Lock
    }
  }
}
</script>

<style scoped>
.main {
  background-image: url("../../assets/img/login.webp");
  background-size: 100% 100%;
  height: 100%;
}

.login_box {
  width: 400px;
  height: 300px;
  background-color: #FFFFFF;
  box-shadow: 0 5px 20px 0 #e8e8e8;
  border-radius: 20px;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  margin: auto;
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  text-align: center;
  margin-top: 30px;
}

.login_form {
  margin-top: 40px;
  margin-right: 30px;
}

.btn {
  margin-left: 36%;
}

.btn .el-button {
  width: 140px;
}
</style>